package com.ac.scum.log.web.utils.ftp;

import com.ac.scum.log.bean.ServerFTP;
import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

@Slf4j
public class FTPUtil {
    private final ServerFTP serverFTP;
    private FTPClient ftpClient;
    private Session session;
    private ChannelSftp sftpChannel;

    public FTPUtil(ServerFTP serverFTP) {
        this.serverFTP = serverFTP;
    }

    public void connect() throws IOException, JSchException {
        if (serverFTP.getSftpFlag()) {
            JSch jsch = new JSch();
            session = jsch.getSession(serverFTP.getUsername(), serverFTP.getIp(), serverFTP.getPort());
            session.setProxy(new ProxySOCKS5("18.179.200.158", 1080));
            session.setPassword(serverFTP.getPassword());
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();
            session.setTimeout(5000);
            Channel channel = session.openChannel("sftp");
            channel.connect();
            sftpChannel = (ChannelSftp) channel;
        } else {
            ftpClient = new FTPClient();
            ftpClient.setProxy(new java.net.Proxy(Proxy.Type.SOCKS, new InetSocketAddress("18.179.200.158", 1080)));
            ftpClient.setConnectTimeout(5000); // 设置连接超时时间为5秒
            ftpClient.connect(serverFTP.getIp(), serverFTP.getPort());
            ftpClient.login(serverFTP.getUsername(), serverFTP.getPassword());
            ftpClient.enterLocalPassiveMode();
        }
    }

    public void disconnect() {
        if (serverFTP.getSftpFlag()) {
            if (sftpChannel != null) {
                sftpChannel.disconnect();
            }
            if (session != null) {
                session.disconnect();
            }
        } else {
            if (ftpClient != null && ftpClient.isConnected()) {
                try {
                    ftpClient.logout();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }

            }
        }
    }

    public boolean isConnected() {
        if (serverFTP.getSftpFlag()) {
            return (session != null && session.isConnected()) || (sftpChannel != null && sftpChannel.isConnected());
        } else {
            return ftpClient != null && ftpClient.isConnected();
        }
    }

    public List<FTPFile> listFiles(String remoteDir) throws IOException, SftpException {
        List<FTPFile> ftpFileList = new ArrayList<>();
        if (serverFTP.getSftpFlag()) {
            sftpChannel.cd(remoteDir);
            assembleSFtpFile(ftpFileList);
        } else {
            FTPFile[] files = ftpClient.listFiles(remoteDir);
            assembleFtpFile(ftpFileList, files);
        }
        return ftpFileList;
    }

    public List<FTPFile> listFiles() throws IOException, SftpException {
        List<FTPFile> ftpFileList = new ArrayList<>();
        if (serverFTP.getSftpFlag()) {
            assembleSFtpFile(ftpFileList);
        } else {
            FTPFile[] files = ftpClient.listFiles();
            assembleFtpFile(ftpFileList, files);
        }
        return ftpFileList;
    }

    private void assembleSFtpFile(List<FTPFile> ftpFileList) throws SftpException {
        Vector<ChannelSftp.LsEntry> files = sftpChannel.ls(".");
        for (ChannelSftp.LsEntry file : files) {
            if (file.getFilename().equals(".") || file.getFilename().equals("..")) {
                continue;
            }
            FTPFile ftpFile = new FTPFile();
            if (file.getAttrs().isDir()) {
                ftpFile.setType(0);
            } else {
                ftpFile.setType(1);
            }
            ftpFile.setSize(file.getAttrs().getSize());
            ftpFile.setName(file.getFilename());
            ftpFileList.add(ftpFile);
        }
    }

    private void assembleFtpFile(List<FTPFile> ftpFileList, FTPFile[] files) {
        for (FTPFile file : files) {
            FTPFile ftpFile = new FTPFile();
            if (file.isDirectory()) {
                ftpFile.setType(0);
            } else {
                ftpFile.setType(1);
            }
            ftpFile.setSize(file.getSize());
            ftpFile.setName(file.getName());
            ftpFileList.add(ftpFile);
        }
    }

    public void downloadFile(String remoteFilePath, String localFilePath) throws IOException, SftpException {
        if (serverFTP.getSftpFlag()) {
            sftpChannel.get(remoteFilePath, localFilePath);
        } else {
            OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(localFilePath));
            ftpClient.retrieveFile(remoteFilePath, outputStream);
            outputStream.close();
        }
    }

    public void uploadFile(String localFilePath, String remoteFilePath) throws IOException, SftpException {
        if (serverFTP.getSftpFlag()) {
            sftpChannel.put(localFilePath, remoteFilePath);
        } else {
            InputStream inputStream = new FileInputStream(localFilePath);
            ftpClient.storeFile(remoteFilePath, inputStream);
            inputStream.close();
        }
    }

    public void processFileInputStream(String remoteFilePath, InputStreamProcessor processor) throws IOException, SftpException {
        InputStream inputStream = null;
        if (serverFTP.getSftpFlag()) {
            inputStream = sftpChannel.get(remoteFilePath);
        } else {
            try {
                inputStream = ftpClient.retrieveFileStream(remoteFilePath);
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }

        if (inputStream != null) {
            try {
                processor.process(inputStream);
            } finally {
                inputStream.close();
            }
        }
    }

    @FunctionalInterface
    public interface InputStreamProcessor {
        void process(InputStream inputStream) throws IOException;
    }
}
